// 学生管理相关功能
const StudentManager = {
    // 加载学生列表
    async loadStudents() {
        loading.show();
        try {
            const students = await API.students.getAll();
            const studentList = document.getElementById('studentList');
            
            if (!students || students.length === 0) {
                studentList.innerHTML = `
                    <div class="empty-state">
                        <p>暂无学生数据</p>
                        <button class="btn btn-primary" onclick="StudentManager.showAddForm()">
                            <i class="icon add-icon"></i>添加学生
                        </button>
                    </div>
                `;
                return;
            }

            studentList.innerHTML = students.map(student => `
                <div class="card">
                    <h3>${student.name}</h3>
                    <p>学号：${student.studentNumber}</p>
                    <p>性别：${student.gender}</p>
                    <p>联系电话：${student.phone || '无'}</p>
                    <p class="text-muted">创建时间：${new Date(student.createdAt).toLocaleString()}</p>
                    <div class="card-actions">
                        <button class="btn btn-primary" onclick="StudentManager.showDetails(${student.id})">
                            <i class="icon student-icon"></i>查看详情
                        </button>
                        <button class="btn btn-primary" onclick="StudentManager.showDisciplineRecords(${student.id})">
                            <i class="icon discipline-icon"></i>违纪记录
                        </button>
                        <button class="btn btn-danger" onclick="StudentManager.delete(${student.id})">
                            <i class="icon delete-icon"></i>删除
                        </button>
                    </div>
                </div>
            `).join('');
        } catch (error) {
            Debug.error('加载学生列表失败', error);
            document.getElementById('studentList').innerHTML = `
                <div class="error-state">
                    <p>加载失败: ${error.message}</p>
                    <button onclick="StudentManager.loadStudents()">重试</button>
                </div>
            `;
        } finally {
            loading.hide();
        }
    },

    // 显示添加表单
    async showAddForm() {
        try {
            Debug.log('显示添加学生表单');
            // 重置表单
            const form = document.getElementById('addStudentForm');
            if (!form) {
                throw new Error('找不到添加学生表单');
            }
            form.reset();

            // 加载宿舍楼选择框
            const buildings = await API.buildings.getAll();
            const buildingSelect = form.querySelector('select[name="buildingId"]');
            if (!buildingSelect) {
                throw new Error('找不到宿舍楼选择框');
            }

            buildingSelect.innerHTML = `
                <option value="">请选择宿舍楼</option>
                ${buildings.map(building => `
                    <option value="${building.id}">${building.buildingName}</option>
                `).join('')}
            `;

            // 重置房间选择框
            const roomSelect = form.querySelector('select[name="roomId"]');
            if (!roomSelect) {
                throw new Error('找不到房间选择框');
            }
            roomSelect.innerHTML = '<option value="">请先选择宿舍楼</option>';

            // 显示模态框
            showModal('addStudentModal');
            Debug.log('添加学生表单已显示');
        } catch (error) {
            Debug.error('初始化添加学生表单失败:', error);
            alert('初始化添加学生表单失败: ' + error.message);
        }
    },

    // 加载房间选择框
    async loadRoomSelect(buildingId) {
        try {
            Debug.log('加载房间选择框, buildingId:', buildingId);
            if (!buildingId) {
                const roomSelect = document.querySelector('#addStudentForm select[name="roomId"]');
                if (!roomSelect) {
                    throw new Error('找不到房间选择框');
                }
                roomSelect.innerHTML = '<option value="">请先选择宿舍楼</option>';
                return;
            }

            const rooms = await API.rooms.getByBuilding(buildingId);
            const roomSelect = document.querySelector('#addStudentForm select[name="roomId"]');
            if (!roomSelect) {
                throw new Error('找不到房间选择框');
            }

            if (!rooms || rooms.length === 0) {
                roomSelect.innerHTML = '<option value="">该宿舍楼暂无可用房间</option>';
                return;
            }

            roomSelect.innerHTML = `
                <option value="">请选择房间</option>
                ${rooms.filter(room => room.currentOccupancy < room.capacity)
                    .map(room => `
                        <option value="${room.id}">
                            ${room.roomNumber} (${room.currentOccupancy}/${room.capacity})
                        </option>
                    `).join('')}
            `;
            Debug.log('房间选择框已更新');
        } catch (error) {
            Debug.error('加载房间列表失败:', error);
            alert('加载房间列表失败: ' + error.message);
        }
    },

    // 显示学生详情
    async showDetails(studentId) {
        try {
            Debug.log('显示学生详情:', studentId);
            loading.show();
            
            const student = await API.students.getById(studentId);
            if (!student) {
                throw new Error('找不到学生信息');
            }

            const modal = document.createElement('div');
            modal.className = 'modal active';
            modal.innerHTML = `
                <div class="modal-content">
                    <button type="button" class="modal-close" onclick="this.closest('.modal').remove()"></button>
                    <h3>学生详情</h3>
                    <div class="student-details">
                        <h4>${student.name}</h4>
                        <p>学号：${student.studentNumber}</p>
                        <p>性别：${student.gender}</p>
                        <p>联系电话：${student.phone || '无'}</p>
                        <p>所在宿舍：${student.room ? 
                            `${student.room.building.buildingName} ${student.room.roomNumber}` : 
                            '<span class="text-muted">未分配</span>'}</p>
                        <p class="text-muted">创建时间：${new Date(student.createdAt).toLocaleString()}</p>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            Debug.log('学生详情已显示');
        } catch (error) {
            Debug.error('获取学生详情失败:', error);
            alert('获取学生详情失败: ' + error.message);
        } finally {
            loading.hide();
        }
    },

    // 删除学生
    async delete(id) {
        if (confirm('确定要删除这个学生吗？删除后将无法恢复。')) {
            try {
                loading.show();
                await API.students.delete(id);
                this.loadStudents();
            } catch (error) {
                Debug.error('删除学生失败:', error);
                alert('删除学生失败: ' + error.message);
            } finally {
                loading.hide();
            }
        }
    },

    // 初始化事件监听
    init() {
        Debug.log('初始化StudentManager');
        // 添加学生表单提交处理
        const addStudentForm = document.getElementById('addStudentForm');
        if (addStudentForm) {
            addStudentForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const formData = new FormData(e.target);
                const student = {
                    studentNumber: formData.get('studentNumber'),
                    name: formData.get('name'),
                    gender: formData.get('gender'),
                    phone: formData.get('phone'),
                    roomId: parseInt(formData.get('roomId'))
                };

                try {
                    loading.show();
                    await API.students.create(student);
                    hideModal('addStudentModal');
                    this.loadStudents();
                    e.target.reset();
                } catch (error) {
                    Debug.error('添加学生失败:', error);
                    alert('添加学生失败: ' + error.message);
                } finally {
                    loading.hide();
                }
            });

            // 监听宿舍楼选择变化
            const buildingSelect = addStudentForm.querySelector('select[name="buildingId"]');
            if (buildingSelect) {
                buildingSelect.addEventListener('change', (e) => {
                    this.loadRoomSelect(e.target.value);
                });
            }
        }
        Debug.log('StudentManager初始化完成');
    }
};

// 确保在页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    StudentManager.init();
});

// 导出全局函数
window.StudentManager = StudentManager; 